package com.upcode.weighing.admin.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class NsopRestTemplateUtil {

    @Bean
    @LoadBalanced
    public static RestTemplate getInstance(String charset) {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if(httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
            }
        }
        return restTemplate;
    }

    public static <T> T postForOBJ(String url, Object obj,ParameterizedTypeReference<T> responseType) throws Exception {

        log.info("======postForSendMQ==========URL==" + url);
        RestTemplate restTemplate = getInstance("utf-8");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<Object> requestEntity = new HttpEntity<>(obj, requestHeaders);
        T baseResult = restTemplate.exchange(url,
                HttpMethod.POST,requestEntity,
                responseType).getBody();
        log.info("======RestTemplateUtil=====" + JSONObject.toJSONString(baseResult));
        return baseResult;
    }
}
